import { getOptions } from "./options";
import fs from "fs";
import { genNode, Node, FILETYPE, ACTIONTYPE, GenNodeParam } from "./genNode";
import { handleContent } from "./handleContent";
import path from "path";
import { getFileKeyValue } from "./getFileKeyValues";

export const logs: string[] = [];
export const errlogs: string[] = [];

const { rootPath, outerPath, lazy, targets, requestInterval } = getOptions();

const getQueue = (nodes: Node[], queue: any[]) => {
  nodes.map((node) => {
    switch (node.fileType) {
      //遇到文件夹就创建文件夹
      case FILETYPE.dir:
        if (lazy && targets?.length) {
          node.targets!.forEach((item) => {
            const path = Object.keys(item)[0];
            try {
              fs.mkdirSync(path);
            } catch (e) {}
          });
        } else {
          fs.mkdirSync(node.outerPath);
        }
        if (node.children) {
          getQueue(node.children, queue);
        }
        break;
      //遇到需要翻译的文件就看要做什么事情
      case FILETYPE.file:
        //如果当时懒翻译状态则解析
        if (lazy && targets?.length) {
          const [rootKeys, rootValues, err] = getFileKeyValue({
            importPath: node.importPath,
          });
          if (err) break;
          node.targets?.forEach((target) => {
            const path = Object.keys(target)[0];
            const lang = target[path];

            queue.push(
              handleContent({
                importPath: path,
                rootKeys,
                rootValues,
                lang,
                node,
              })
            );
          });
        } else {
          queue.push(
            handleContent({
              importPath: node.importPath,
              node,
              outerPath: node.outerPath,
            })
          );
        }
        break;
      //遇到index文件和其他文件就原封不动的创建
      case FILETYPE.unknown:
      case FILETYPE.index:
        if (lazy && targets?.length) {
          node.targets!.forEach((item) => {
            const path = Object.keys(item)[0];
            try {
              const data = fs.readFileSync(node.importPath, "utf-8");
              fs.writeFileSync(path, data);
            } catch (e) {}
          });
        } else {
          const data = fs.readFileSync(node.importPath, "utf-8");
          fs.writeFileSync(node.outerPath, data);
        }
        node.done = true;
        node.msg = "文件复制成功,该文件不是需要翻译的类型";
        break;
    }
  });
};

export const main = () => {
  const queue: any[] = [];
  const fileList = fs.readdirSync(rootPath as string);

  const nodes = genNode({
    importPath: rootPath as string,
    outerPath: outerPath as string,
    fileList,
    targets: lazy && targets?.length ? targets : null,
  });
  
  getQueue(nodes, queue);

  function* gen() {
    for (let i = 0; i < queue.length; i++) {
      yield queue[i];
    }
  }

  const tasks = gen();
  function fun() {
    const res = tasks.next();

    if (res.done) {
      // fs.writeFileSync(
      //   path.join(outerPath as string, "successLog.txt"),
      //   logs.join("\n")
      // );
      // fs.writeFileSync(
      //   path.join(outerPath as string, "errorLog.txt"),
      //   errlogs.join("\n")
      // );
      // fs.writeFileSync(
      //   path.join(outerPath as string, "info.json"),
      //   JSON.stringify(nodes)
      // );
      console.log(
        `\n成功翻译:${logs.length}个文件 报告地址:${path.join(
          outerPath as string,
          "successLog.txt"
        )}`
      );
      console.log(
        `失败:${errlogs.length}个文件 报告地址:${path.join(
          outerPath as string,
          "errorLog.txt"
        )}`
      );
      console.log(
        `具体信息文件位置:${path.join(outerPath as string, "info.json")}`
      );

      return;
    }

    res.value?.().then((info: string) => {
      console.log(info);
      setTimeout(() => {
        fun();
      }, requestInterval || 1100);
    });
  }

  fun();
};
